<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Document</title>
  <link rel="stylesheet" href="./assets/news.css" />
  <script src="./lib/jquery.js"></script>
  <script src="./lib/template-web.js"></script>
  <script id="cmt_list" type="text/html">
    {{each data}}
    <div class="news-item">
      <img class="thumb" src="{{'http://www.liulongbin.top:3006' + $value.img}}" alt=""/>
      <div class="right-box">
        <h1 class="title">{{$value.title}}</h1>
        <div class="tags">
         {{each $value.tags}}
         <span>{{$value}}</span>
         {{/each}}
        </div>
        <div class="footer">
          <div>
            <span>{{$value.source}}</span>&nbsp;&nbsp;
            <span>{{$value.time | dateFormat }}</span>
          </div>
          <span>评论数：{{$value.cmtcount}}</span>
        </div>
      </div>
    </div>
    {{/each}}
    </script>
</head>

<body>

  <div id="news-list">

  </div>
  <script type="text/javascript">
    function padZero(n) {
      // 三目运算符
      return n < 10 ? '0' + n : n
      // if (n < 10) {
      //   // 如果是个位数就补零
      //   return '0' + n
      // } else {
      //   // 不是个位数就原封不动返回
      //   return n
      // }
    }
    //定义时间过滤器
    template.defaults.imports.dateFormat = function (dtStr) {
      var dt = new Date(dtStr)

      var y = dt.getFullYear()
      var m = padZero(dt.getMonth() + 1)
      var d = padZero(dt.getDate())

      var hh = padZero(dt.getHours())
      var mm = padZero(dt.getMinutes())
      var ss = padZero(dt.getSeconds())

      return y + '-' + m + '-' + d + ' ' + hh + ':' + mm + ':' + ss
    }
    function loadNewsList() {
      $.get('http://www.liulongbin.top:3006/api/news', function (res) {
        // console.log(res)
        if (res.status === 200) {
          res.data.forEach(function (item) {
            // 把字符串分割成数组
            item.tags = item.tags.split(',')
          })
          // var list = res.data;
          var ret = template('cmt_list', res)
          $("#news-list").html(ret)
        }
      })
    }
    loadNewsList()
  </script>
</body>

</html>